const Service = require('egg').Service;

var uuid = require('uuid');

class MenuService extends Service {

	async list () {
		const res = await this.app.mysql.get('sys').query(
			' select id, code, name from dlq_role ' + 
			' where del_flag = "0" '
		);
		return res;
	}

	async create (code, name) {
		const res = await this.app.mysql.get('sys').query(
			' insert into dlq_role ' + 
			' (id, code, name, create_time, update_time) ' + 
			' values ' + 
			' (uuid(), ?, ?, now(), now()) ', [code, name]
		);

		console.log(res);

		return res.affectedRows === 1;
	}

	async update (name, code, id) {
		const res = await this.app.mysql.get('sys').query(
			' update dlq_role set ' + 
			' name = ?, code = ?, update_time = now() ' + 
			' where ' + 
			' id = ? ', [name, code, id]
		);

		console.log(res);

		return res.affectedRows === 1;
	}

	async delete (id) {
		const res = await this.app.mysql.get('sys').query(
			' update dlq_role set ' + 
			' del_flag = "1", update_time = now() ' + 
			' where ' + 
			' id = ? ', [id]
		);

		console.log(res);

		return res.affectedRows === 1;
	}


	async getListByUserid (id) {

		const auth = await this.app.mysql.get('sys').query(
			' select r.id, code, name from dlq_role as r ' +
			' left join dlq_user_role as ur on r.id = ur.role_id ' +
			' where ur.user_id = ? ', [id]
		);	

		return auth;
	}

	async setMenu (roleId, menuIdsChecked, menuIdsUnchecked) {

		const result = await this.app.mysql.get('sys').beginTransactionScope(async conn => {
			
			let res = await conn.delete('dlq_role_menu', {
				role_id : roleId,
			});

			console.log(res);

			const mc = menuIdsChecked.split(',');

			let arr = [];
			mc.forEach(menuid => {
				if(menuid != ''){
					arr.push({
						id : uuid.v1(),
						role_id : roleId,
						menu_id : menuid,
						checked : '1',
					});
				}
			})

			const muc = menuIdsUnchecked.split(',');
			muc.forEach(menuid => {
				if(menuid != ''){
					arr.push({
						id : uuid.v1(),
						role_id : roleId,
						menu_id : menuid,
						checked : '0',
					});
				}
			})

			let res1 = await conn.insert('dlq_role_menu', arr);

			console.log(res1);

			return true;

		}, this.ctx);


		return result;
	}
}

module.exports = MenuService;